package com.hh;

import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class RefreshCsdnBlogService implements InitializingBean {

    @Value("${blog.urls}")
    List<String> urls;
    @Value("${blog.startup:false}")
    boolean startup;

    // @Scheduled(cron = "0 0/1 0-23 * * ?")
    public void refreshBlog() {
        log.info("博客url列表:");
        for (String url : urls) {
            log.info(url);
        }
        int start = 5 * 60;
        int end = 30 * 60;
        doFresh();
        Random r = new Random();
        while (true) {
            // 5分钟300s - 20分钟1200s 内随机
            int millis = r.nextInt(end - start) + start;
            log.info("下次刷新：" + millis + "秒后");
            sleep(millis);
            doFresh();
        }


    }

    private void doFresh() {
        try {
            for (String url : urls) {
                String s = HttpUtil.get(url);
                log.info("执行了：" + url);
            }
            log.info("");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (startup)
            new Thread(() -> refreshBlog()).start();
    }

    private void sleep(int second) {
        try {
            Thread.sleep(second * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
